package org.finir.fakturisanje.business.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.finir.fakturisanje.business.service.jasper.DataPopulation;
import org.finir.fakturisanje.business.service.jasper.FakturaVar;
import org.finir.fakturisanje.persistence.Faktura;

public class StampanjeFaktureImpl implements StampanjeFakture {

	/* (non-Javadoc)
	 * @see org.finir.fakturisanje.business.service.StampanjeFakture#odstampajFakturu(org.finir.fakturisanje.persistence.Faktura)
	 */
	public void odstampajFakturu(Faktura faktura) {

		try {
			ExternalContext context = FacesContext.getCurrentInstance()
					.getExternalContext();
			HttpServletResponse response = (HttpServletResponse) context
					.getResponse();

			response.setContentType("application/pdf");
			/*
			 * response.addHeader("Content-Disposition", "attachment;filename="
			 * + "faktura_br." + faktura.getBrojFakture());
			 */

			List<FakturaVar> data = DataPopulation.pupulateFaktura(faktura,
					faktura.getStavkeFakture());

			JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(data);

			Map map = DataPopulation.pupulateFakturaMap(faktura);
			InputStream reportStream = context
					.getResourceAsStream("/reports/PoreskaFaktura.jasper");

			byte[] runReportToPdf = JasperRunManager.runReportToPdf(
					reportStream, map, ds);

			response.setContentLength(runReportToPdf.length);
			OutputStream writer = response.getOutputStream();
			writer.write(runReportToPdf, 0, runReportToPdf.length);

			writer.flush();
			writer.close();

			FacesContext.getCurrentInstance().responseComplete();
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
